import { isValidIP, isValidPort } from "./utils.js";

const scene = new Image();
const canvas = document.querySelector("#global-view");
// 设置canvas大小
const width = (canvas.width = 1800 - 72);
const height = (canvas.height = 960 - 80 - 96);
const scaleX = width / 800;
const scaleY = height / 600;
const ctx = canvas.getContext("2d");

const toast = document.querySelector("#toast");
const toastText = document.querySelector("#toast .toast-body");
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toast);
const sceneSelect = document.querySelector("#scene-select");
const trajSelect = document.querySelector("#traj-select");
// const poseSelect = document.querySelector("#pose-select");
// const angleInput = document.querySelector("#angle-input");
const targetIp = document.querySelector("#target-ip");
const targetPort = document.querySelector("#target-port");
const submitBtn = document.querySelector("#submit-btn");
// 自动加载下位机地址和端口
targetIp.value = window.localStorage.getItem("targetIp");
targetPort.value = window.localStorage.getItem("targetPort");

// 在canvas中画出轨迹点
function drawPoints(trajType) {
  let points;
  points = trajs[`trajectory_${trajType}`];
  ctx.fillStyle = "red";
  for (let point of points) {
    ctx.beginPath();
    ctx.arc(
      (point[0] + 100) * scaleX,
      (point[1] + 100) * scaleY,
      4,
      0,
      Math.PI * 2
    );
    ctx.fill();
  }
}

function draw() {
  ctx.clearRect(0, 0, width, height);
  scene.src = sceneSelect.value;
  scene.onload = () => {
    ctx.drawImage(scene, 0, 0, width, height);
    drawPoints(trajSelect.value);
  };
}

function initSceneSelect(scenes) {
  scenes.forEach((item) => {
    const option = document.createElement("option");
    option.value = item.path;
    option.text = item.name.split(".")[0];
    sceneSelect.add(option);
  });
}

// 获取静态轨迹waypoints
let trajs = null;
fetch("trajectories.json")
  .then((res) => res.json())
  .then((data) => {
    trajs = data;
  });

let scenes = null;
fetch("/scenes")
  .then((res) => res.json())
  .then((data) => {
    scenes = data;
    initSceneSelect(scenes);
  });

setTimeout(draw, 100);

sceneSelect.addEventListener("change", draw);

trajSelect.addEventListener("change", draw);

// poseSelect.addEventListener("change", () => {
//   if (poseSelect.value === "leo") {
//     angleInput.value = 0;
//     // leo轨道不能改变倾角
//     angleInput.disabled = true;
//   } else if (poseSelect.value === "meo") {
//     angleInput.value = 0;
//     angleInput.disabled = false;
//     angleInput.min = 0;
//     angleInput.max = 55;
//   } else if (poseSelect.value === "heo") {
//     angleInput.value = 55;
//     angleInput.disabled = false;
//     angleInput.min = 55;
//     angleInput.max = 90;
//   }
// });

// angleInput.addEventListener("change", () => {
//   // 倾角必须在范围内
//   angleInput.value = Number(angleInput.value);
//   if (angleInput.validity.rangeUnderflow) {
//     angleInput.value = angleInput.min;
//   }
//   if (angleInput.validity.rangeOverflow) {
//     angleInput.value = angleInput.max;
//   }
// });

submitBtn.addEventListener("click", (e) => {
  if (!isValidIP(targetIp.value)) {
    toastText.textContent = "请输入正确的IP地址";
    toastBootstrap.show();
    return;
  }
  if (!isValidPort(targetPort.value)) {
    toastText.textContent = "请输入正确的端口号";
    toastBootstrap.show();
    return;
  }
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      // scene: scenes[sceneSelect.selectedIndex].name.split(".")[0],
      scene: sceneSelect.selectedOptions[0].textContent,
      traj: trajSelect.value,
      // angle: angleInput.value,
      targetIp: targetIp.value,
      targetPort: targetPort.value,
    }),
  };
  fetch("/run-next", options)
    .then((res) => res.json())
    .then((data) => {
      if (data.code === 0) {
        // 如果下位机激活成功则保存地址
        window.localStorage.setItem("targetIp", targetIp.value);
        window.localStorage.setItem("targetPort", targetPort.value);
      } else {
        toastText.textContent = data.message;
        toastBootstrap.show();
      }
    });
});
